import Vue from 'vue'
import Component from './func-notification'

//通过extend方法创建
const NotificationConstractor = Vue.extend(Component)
// 属性数组
const instances = []
// 控制每次生成的instanc的id都不同
let seed = 1

// 移除节点，位移往下调
const removeInstance = (instance) => {
  if (!instance) return
  const len = instances.length
  const index = instances.findIndex(inst => instance.id === inst.id)

  instances.splice(index, 1)

  if (len <= 1) return
  const removeHeight = instance.vm.height
  for (let i = index; i < len - 1; i++) {
    instances[i].verticalOffset =
      parseInt(instances[i].verticalOffset) - removeHeight - 16
  }
}
const notify = (options) => {
  // 判断是否是服务端，设计dom操作，服务端没有dom操作
  if (Vue.prototype.$isServer) return
  // 扩展的属性
  const {
    autoClose,
    ...rest
  } = options
  const instance = new NotificationConstractor({
    propsData: {
      ...rest
    },
    data: {
      autoClose: autoClose === undefined ? 3000 : autoClose // 出现autoClose为undefinedS
    }
  })

  const id = `notification_${seed++}`
  instance.id = id
  instance.vm = instance.$mount()
  // 将instance 挂载到body下面
  document.body.appendChild(instance.vm.$el)
  // 插入之后，才会去显示
  instance.vm.visible = true

  // 每个通知的垂直距离
  let verticalOffset = 0
  instances.forEach(item => {
    verticalOffset += item.$el.offsetHeight + 16
  })
  verticalOffset += 16
  instance.verticalOffset = verticalOffset
  instances.push(instance)
  // 监听关闭事假,销毁数据
  instance.vm.$on('closed', () => {
    removeInstance(instance)
    document.body.removeChild(instance.vm.$el)
    instance.vm.$destroy()
  })
  instance.vm.$on('close', () => {
    instance.vm.visible = false
  })
  return instance.vm
}

export default notify
